<template>
  <a-row class="container">
    <div class="btn-area">
      <!-- <a-col :span="6"> -->
      <div class="search" >

      </div>
      <div class="two-btn">
        <a-input-search  @search="onSearch"  placeholder="搜索设备(ID/IP/教室)"  class="search" enter-button />
        <button class="content-btn" @click="addDevice">
          添加设备
        </button>
        <button class="content-btn" @click="bulkImport_visible = true">
          批量添加
        </button>
      </div>
      <!-- </a-col> -->
      <!-- 批量导入modal -->
      <batchAddDevices
        @refresh="refresh++"
        :visible.sync="bulkImport_visible"
      ></batchAddDevices>
    </div>

    <a-modal v-model="edit_visible" title="编辑设备" @ok="editSubmit" @cancel="editCancel">
      <a-form
        :model="deviceForm"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 12 }"
      >
        <a-form-model-item label="设备ID">
          {{ deviceForm.deviceID }}
        </a-form-model-item>
        <a-form-model-item label="IP">
          {{ deviceForm.deviceIP }}
        </a-form-model-item>
        <a-form-model-item label="所属建筑">
          <a-tree-select
            :value="selectValue"
            allow-clear
            tree-default-expand-all
            @change="campusAndBuilding"
          >
            <a-tree-select-node
              :selectable="false"
              :key="campus.campus_name"
              :value="`${campus._id}#`"
              :title="campus.campus_name"
              v-for="campus in campusList"
            >
              <a-tree-select-node
                :key="buildings.building_name"
                :value="`${campus._id}:${buildings._id}`"
                :title="buildings.building_name"
                v-for="buildings in campus.buildings"
              >
              </a-tree-select-node>
            </a-tree-select-node>

          </a-tree-select>
        </a-form-model-item>
        <a-form-model-item label="所属教室">
          <a-select v-model="deviceForm.deviceRoom.room_number" style="width: 100%">
            <a-select-option v-for="room in rooms" :key="room._id">
              编号：{{ room.room_number }} -- 类型： {{ room.room_type }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="设备MAC">
          {{ deviceForm.deviceMAC }}
        </a-form-model-item>
        <a-form-model-item label="状态">
          {{deviceForm.status}}
        </a-form-model-item>
      </a-form>
    </a-modal>

    <a-spin :spinning="spinStatus">
      <a-table
        rowkey="_id"
        size="small"
        :columns="columns"
        :data-source="deviceData"
        :row-selection="rowSelection"
        bordered
        :pagination="{
          'hide-on-single-page': true,
          defaultPageSize: 20,
        }"
      >
        <template slot="address" slot-scope="text, record">
          {{
            `${record.deviceCampus.campus_name}-${record.deviceBuilding.building_name}-${record.deviceRoom.room_number}`
          }}
        </template>
        <template slot="操作" slot-scope="text, record">
          <div class="editable-row-operations">
            <a-space>
              <a @click="editDevice(record)">编辑</a>
              <a @click="connectDevice(record)">连接</a>
              <a @click="deleteDevice(record.id)">删除</a>
            </a-space>
          </div>
        </template>
        <template slot="status" slot-scope="text">
          <a-tag color="#388e3c" v-if="text == '已连接'"> 已连接</a-tag>
          <a-tag color="#ff5252" v-else> 未连接</a-tag>
        </template>
      </a-table>
    </a-spin>
    <!-- 添加房间 -->
    <a-modal
      v-model="addDeviceVisible"
      title="添加房间"
      @ok="submitAddDevice"
      :maskClosable="false"
    >
      <a-form-model :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="学校">
          {{ orgName }}
        </a-form-model-item>
        <a-form-model-item label="所属建筑">
          <a-tree-select
            :value="selectValue"
            allow-clear
            tree-default-expand-all
            @change="campusAndBuilding"
          >
            <a-tree-select-node
              :selectable="false"
              :key="campus.campus_name"
              :value="`${campus._id}#`"
              :title="campus.campus_name"
              v-for="campus in campusList"
            >
              <a-tree-select-node
                :key="buildings.building_name"
                :value="`${campus._id}:${buildings._id}`"
                :title="buildings.building_name"
                v-for="buildings in campus.buildings"
              >
              </a-tree-select-node>
            </a-tree-select-node>
          </a-tree-select>
        </a-form-model-item>
        <a-form-model-item label="所属教室">
          <a-select v-model="deviceForm.deviceRoom" style="width: 100%">
            <a-select-option v-for="room in rooms" :key="room._id">
              编号：{{ room.room_number }} -- 类型： {{ room.room_type }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="设备IP">
          <a-input
            placeholder="请输入设备IP"
            v-model="deviceForm.deviceIP"
          ></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-row>
</template>

<script>
import axios from "@/utils/axios";
import { mapState } from "vuex";
import batchAddDevices from "./BatchAddDevices";

const columns = [
  {
    title: "设备ID",
    dataIndex: "deviceID",
    align: "center",
    width: "150px",
  },
  {
    title: "设备IP",
    dataIndex: "deviceIP",
    align: "center",
    width: "150px",
  },
  {
    title: "设备地点",
    dataIndex: "address",
    align: "center",
    width: "450px",
    scopedSlots: { customRender: "address" },
  },
  // deviceMAC
  {
    title: "设备MAC",
    dataIndex: "deviceMAC",
    align: "center",
    width: "150px",
  },
  {
    title: "设备状态",
    dataIndex: "status",
    align: "center",
    scopedSlots: { customRender: "status" },
  },
  {
    title: "操作",
    dataIndex: "操作",
    align: "center",
    scopedSlots: { customRender: "操作" },
  },
];
const rowSelection = {};
export default {
  components: {
    batchAddDevices,
  },
  data() {
    return {
      // 加载
      edit_visible:false,
      spinStatus: false,
      bulkImport_visible: false,
      refresh: 0,
      selectValue: "",
      org_name: this.orgName,
      // 表单
     deviceForm: {
        deviceBuilding: "",
        deviceRoom: "",
        deviceIP: "",
        deviceID:"",
        deviceMAC: "",
        address:"",
        status:"",
        deviceCampus: "",
      },
      // modalVisible
      addDeviceVisible: false,
      // other
      campusList: [],
      deviceData: [],
      deviceDatas: [],
      deviceDatass: [],
      rooms: [],
      columns,
      editingKey: "",
      rowSelection,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
    };
  },
  watch: {
  refresh() {
      this.getAllDevices();
    },
  },
  created(){
    this.getAllDevices();
  },
  mounted() {
    this.spaceList();
  },
  methods: {
    async connectDevice(record) {
      const url = "/pc/v1/devices/checkConnect";
      let { data } = await axios.post(url, {
        deviceIP: record.deviceIP,
        _id: record._id,
      });
      if (data.status == "fail") {
        this.$message.error(data.message);
        return;
      }
      this.$message.info("连接成功！");
    },
    async getAllDevices() {
      this.spinStatus = true;
      const url = "/pc/v1/devices";
      let { data } = await axios.get(url, "", 1000000);
      this.deviceData = data.data.devices;
      this.deviceDatas = data.data.devices;
      this.spinStatus = false;
    },
    async submitAddDevice() {
      try {
        const url = "/pc/v1/devices";
        const requestBody = { ...this.deviceForm, orgName: this.orgName };
        let { data } = await axios.post(url, requestBody);
        if (data.status == "fail") {
          this.$message.error(data.message);
          this.refresh++;
          this.addDeviceVisible = false;
          return;
        }
        this.$message.info("添加成功");
        this.refresh++;
        this.addDeviceVisible = false;
      } catch (err) {
        this.$message.error("添加失败");
        console.log(err);
      }
    },
    async spaceList() {
      // 获取空间
      let queryString = "";
      const url = "/pc/v1/campus" + queryString;
      try {
        const { data } = await axios.get(url);
        this.campusList = data.data.campus;
      } catch (err) {
        console.log(err);
      }
    },
  async campusAndBuilding(params, label) {
      params = params.split(":");
      this.deviceForm.deviceCampus = params[0];
      this.deviceForm.deviceBuilding = params[1];
      this.selectValue = label;
      let payload = {
        campus_id: params[0],
        building_id: params[1],
      };
      this.getRooms(payload);
    },
    addDevice(){
      this.addDeviceVisible = true;
      this.selectValue = "";
      this.deviceForm.deviceRoom = "";
      this.deviceForm.deviceIP = "";
    },
    getRooms(payload) {
      // this.building_id = this.deviceForm.deviceBuilding.building_name;
      const url =
        "/pc/v1/rooms/getRoomByCampusOrBuilding" +
        "?building_id=" +
        payload.building_id;
      this.$store
        .dispatch("admin/getTreeByURL", url)
        .then((response) => {
          this.rooms = response.data.data.rooms;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    editDevice(record){
      this.edit_visible = true;
      this.deviceForm = record;
      this.device_ID = record._id;
      this.selectValue = record.deviceBuilding.building_name;
      console.log(this.deviceForm.deviceBuilding._id);
      let payload = {
        campus_id: this.deviceForm.campus_id,
        building_id: this.deviceForm.deviceBuilding._id,
      };
      this.getRooms(payload);
    },
    editCancel() {
      this.getAllDevices();
    },
    async editSubmit(){
      try{
        const url = `/pc/v1/devices/${this.device_ID}`;
        let requestBody = {
          deviceRoom:this.deviceForm.deviceRoom.room_number,
          deviceBuilding:this.deviceForm.deviceBuilding,
        }
        const result = await axios.patch(url, requestBody);
        this.$message.info("编辑成功");
      } catch (err){
        this.$message.error("编辑失败");
      }
      this.getAllDevices();
      this.edit_visible = false;
    },
    onSearch(val){    
      this.deviceDatass = this.deviceDatas;
      if (val == ""){
         this.deviceDatass =  this.deviceDatass.filter((device) => {
          // if(!device.deviceID){
          //   return;
          // }
          return device.deviceID == "";
        });
      }
      else{      
        this.deviceDatass =  this.deviceDatass.filter((device) => {
          device.deviceRoom.room_number = device.deviceRoom.room_number + "";
          return device.deviceID.includes(val) || device.deviceIP.includes(val) || device.deviceBuilding.building_name.includes(val)  || device.deviceCampus.campus_name.includes(val) || device.deviceRoom.room_number.includes(val);
        });
      console.log(this.deviceDatass);
      }
      this.deviceData = this.deviceDatass;
    },
    async deleteDevice(deviceID) {
      var that = this;
      this.$confirm({
        title: "确定删除此资源吗?",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        async onOk() {
          try {
            const url = "pc/v1/devices/" + deviceID;
            await axios.delete(url);
            that.$message.info("删除成功!");
            that.getAllDevices();
          } catch (err) {
            that.$message.error("删除失败");
            console.log(err);
          }
        },
      });
    },
  },
  computed: {
    ...mapState({
      orgName: (state) => state.public.orgName,
    }),
  },
};
</script>

<style lang="scss" scoped>
.search{
  left: 10px;
  display: flex;
  // display: flex;
  width: 200px;
}

.container {
  padding: 20px;
}

::v-deep .ant-table-row {
  padding-top: 0;
}
::v-deep .ant-table-small > .ant-table-content > .ant-table-body {
  margin: 0;
}
::v-deep
  .ant-table-small
  > .ant-table-content
  > .ant-table-body
  > table
  > .ant-table-tbody
  > tr
  > td {
  padding: 5px 5px;
}
</style>
